package com.hqw.mindanews;

import java.io.File;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.datatype.BmobFile;
import cn.bmob.v3.listener.SaveListener;
import cn.bmob.v3.listener.UpdateListener;
import cn.pedant.SweetAlert.SweetAlertDialog;
import cn.pedant.SweetAlert.SweetAlertDialog.OnSweetClickListener;

import com.bmob.BmobProFile;
import com.bmob.btp.callback.UploadListener;
import com.hqw.mindanews.application.SysApplication;
import com.hqw.mindanews.bean.User;
import com.hqw.mindanews.log.Log;
import com.hqw.mindanews.utils.FileUtils;

public class SettingActivity extends FragmentActivity implements
		OnClickListener {
	private static String photoPath = "/sdcard/mindanews/";
	private TextView mBack;
	private ImageView mHead;
	private User currentUser;
	private ImageView imageView;  
	private TextView mUserName;
	private Dialog dialog;
	private String mUserHeadBase64 = null;
	private RelativeLayout mUserNameSet;  
	private TextView mLogOut;
	@Override
	protected void onCreate(Bundle arg0) {
		// TODO Auto-generated method stub
		super.onCreate(arg0);
		setContentView(R.layout.fragment_settings);
		currentUser = BmobUser.getCurrentUser(SettingActivity.this, User.class);
		init();
		SysApplication.getInstance().addActivity(this);
	}

	private void init() {
		mLogOut = (TextView) findViewById(R.id.user_logout);
		mLogOut.setOnClickListener(this);
		mUserName = (TextView) findViewById(R.id.user_nick_text);
		if (currentUser != null) {
			mUserName.setText(currentUser.getUsername());
		}

		mBack = (TextView) findViewById(R.id.back_text);
		mBack.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});

		mHead = (ImageView) findViewById(R.id.user_icon_image);
		if (currentUser != null ) {
			if (currentUser.getBmobFile()!=null) {
				//加载头像
				Log.i("bmob","加载头像");
				currentUser.getBmobFile().loadImage(SettingActivity.this, mHead);

			}
			
		}
		mHead.setOnClickListener(this);
		
		mUserNameSet = (RelativeLayout) findViewById(R.id.user_nick);
		mUserNameSet.setOnClickListener(this);
		
	}

	/**
	 * 显示选择图片对话框
	 */
	private void showDialog() {
		View view = getLayoutInflater().inflate(R.layout.photo_choose_dialog,
				null);
		dialog = new Dialog(this, R.style.transparentFrameWindowStyle);
		dialog.setContentView(view, new LayoutParams(LayoutParams.FILL_PARENT,
				LayoutParams.WRAP_CONTENT));
		Window window = dialog.getWindow();
		// 动画
		window.setWindowAnimations(R.style.main_menu_animstyle);
		WindowManager.LayoutParams wl = window.getAttributes();
		wl.x = 0;
		wl.y = getWindowManager().getDefaultDisplay().getHeight();
		// 宽高
		wl.width = ViewGroup.LayoutParams.MATCH_PARENT;
		wl.height = ViewGroup.LayoutParams.WRAP_CONTENT;

		//
		dialog.onWindowAttributesChanged(wl);
		// 点击屏幕取消选择
		dialog.setCanceledOnTouchOutside(true);

		dialog.show();
		Button choiceFromLib = (Button) view.findViewById(R.id.choice_from_lib);
		choiceFromLib.setOnClickListener(this);

		Button takePic = (Button) view.findViewById(R.id.take_pic);

		takePic.setOnClickListener(this);
		Button choiceCancel = (Button) view.findViewById(R.id.choice_cancel);

		choiceCancel.setOnClickListener(this);

	}

	private void takePic() {
		/**
		 * 下面这句还是老样子，调用快速拍照功能，至于为什么叫快速拍照，大家可以参考如下官方
		 * 文档，you_sdk_path/docs/guide/topics/media/camera.html
		 * 我刚看的时候因为太长就认真看，其实是错的，这个里面有用的太多了，所以大家不要认为
		 * 官方文档太长了就不看了，其实是错的，这个地方小马也错了，必须改正
		 */
		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		// 下面这句指定调用相机拍照后的照片存储的路径
		intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(
				Environment.getExternalStorageDirectory(), "xiaohei.jpg")));
		startActivityForResult(intent, 2);
	}

	private void pickPic() {
		Intent intent = new Intent(Intent.ACTION_PICK, null);

		/**
		 * 下面这句话，与其它方式写是一样的效果，如果：
		 * intent.setData(MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
		 * intent.setType(""image/*");设置数据类型
		 * 如果朋友们要限制上传到服务器的图片类型时可以直接写如："image/jpeg 、 image/png等的类型"
		 * 这个地方小马有个疑问，希望高手解答下：就是这个数据URI与类型为什么要分两种形式来写呀？有什么区别？
		 */
		intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
				"image/*");
		startActivityForResult(intent, 1);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.user_logout :
			new SweetAlertDialog(this).setTitleText("确定退出吗 >_<").showCancelButton(true).setConfirmClickListener(new OnSweetClickListener() {
				
				@Override
				public void onClick(SweetAlertDialog sweetAlertDialog) {
					currentUser.logOut(SettingActivity.this);
					SysApplication.getInstance().exit();
					sweetAlertDialog.dismiss();
				}
			}).show();
			break;
		case R.id.user_icon_image:

			Log.i("bmob", "jinlai");
			showDialog();
			break;
		case R.id.choice_from_lib:
			dialog.dismiss();
			Log.i("bmob", "选择相片");
			pickPic();
			break;
		case R.id.take_pic:
			dialog.dismiss();
			Log.i("bmob", "拍照");
			takePic();
			break;
		case R.id.choice_cancel:
			Log.i("bmob", "取消选择");
			dialog.dismiss();
			break;
		case R.id.user_nick:
			Log.i("bmob", "修改昵称");
//			 final EditText inputServer = new EditText(this);
//		        AlertDialog.Builder builder = new AlertDialog.Builder(this);
//		      
//		        builder.setTitle("修改昵称").setIcon(android.R.drawable.ic_dialog_info).setView(inputServer)
//		                .setNegativeButton("取消", null);
//		        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
//
//		            public void onClick(DialogInterface dialog, int which) {
//		               inputServer.getText().toString();
//		             }
//		        });
//		        builder.show();
			String preString = currentUser.getUsername(); 
			new SweetAlertDialog(this).showCancelButton(true).setTitleText("修改昵称").setSweetAlertEditText(preString).setConfirmClickListener(new OnSweetClickListener() {
				
				@Override
				public void onClick(SweetAlertDialog sweetAlertDialog) {
				  String newUserName = sweetAlertDialog.getSweetAlertEditText();
					Log.i("bmob",newUserName);
					currentUser.setUsername(newUserName);
					currentUser.update(SettingActivity.this);
					mUserName.setText(newUserName);
					sweetAlertDialog.dismiss();
					
				}
			}).show(); 
			break;
			
		default:
			break;
		}
	}

 
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {

		switch (requestCode) {
		// 如果是直接从相册获取
		case 1:
			startPhotoZoom(data.getData());
			break;
		// 如果是调用相机拍照时
		case 2:
			File temp = new File(Environment.getExternalStorageDirectory()
					+ "/xiaoma.jpg");
			startPhotoZoom(Uri.fromFile(temp));
			break;
		// 取得裁剪后的图片
		case 3:
			/**
			 * 非空判断大家一定要验证，如果不验证的话， 在剪裁之后如果发现不满意，要重新裁剪，丢弃
			 * 当前功能时，会报NullException，小马只 在这个地方加下，大家可以根据不同情况在合适的 地方做判断处理类似情况
			 * 
			 */
			if (data != null) {
				setPicToView(data);
			}
			break;
		default:
			break;

		}

		super.onActivityResult(requestCode, resultCode, data);
	}

	/**
	 * 裁剪图片方法实现
	 * 
	 * @param uri
	 */
	public void startPhotoZoom(Uri uri) {
		/*
		 * 至于下面这个Intent的ACTION是怎么知道的，大家可以看下自己路径下的如下网页
		 * yourself_sdk_path/docs/reference/android/content/Intent.html
		 * 直接在里面Ctrl+F搜：CROP ，之前小马没仔细看过，其实安卓系统早已经有自带图片裁剪功能, 是直接调本地库的，小马不懂C C++
		 * 这个不做详细了解去了，有轮子就用轮子，不再研究轮子是怎么 制做的了...吼吼
		 */
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(uri, "image/*");
		// 下面这个crop=true是设置在开启的Intent中设置显示的VIEW可裁剪
		intent.putExtra("crop", "true");
		// aspectX aspectY 是宽高的比例
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
	
		// outputX outputY 是裁剪图片宽高
		intent.putExtra("outputX", 150);
		intent.putExtra("outputY", 150);
		intent.putExtra("return-data", true);
		startActivityForResult(intent, 3);
	}

	/**
	 * 保存裁剪之后的图片数据
	 * 
	 * @param picdata
	 */
	private void setPicToView(Intent picdata) {
		Bundle extras = picdata.getExtras();
		if (extras != null) {

			Bitmap photo = extras.getParcelable("data");
			Drawable drawable = new BitmapDrawable(photo);

			String userHeadFileName = currentUser.getMobilePhoneNumber();
		
			FileUtils.saveBitmap(photo, userHeadFileName);
			
			String filePath = FileUtils.SDPATH + userHeadFileName+ ".JPEG";
			Log.i("bmob",filePath);
			BmobProFile.getInstance(SettingActivity.this).upload(filePath,
					new UploadListener() {

						@Override
						public void onError(int arg0, String arg1) {
							 Log.i("bmob",arg1);

						}

						@Override
						public void onSuccess(String arg0, String arg1,
								BmobFile arg2) {
							FileUtils.deleteDir();
							Toast.makeText(SettingActivity.this, "头像保存成功",
									Toast.LENGTH_LONG).show();
							currentUser = BmobUser.getCurrentUser(SettingActivity.this, User.class);
							currentUser.setBmobFile(arg2);
							currentUser.update(SettingActivity.this,new UpdateListener() {
								
								@Override
								public void onSuccess() {
									// TODO Auto-generated method stub
									currentUser.getBmobFile().loadImage(SettingActivity.this, mHead);
								}
								
								@Override
								public void onFailure(int arg0, String arg1) {
									 
									 Log.i("bmob",arg1);
								}
							});
						}

						@Override
						public void onProgress(int arg0) {
					 
							 Log.i("bmob",arg0);
						}
					});

			
			// iv.setBackgroundDrawable(drawable);
		}
	}

}
